package com.demo.controller;

import com.demo.entity.Speed;
import com.demo.entity.SubSpeed;
import com.demo.service.OilService;
import com.demo.service.SpeedService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.FileWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin(origins = "*")
@Controller
public class SpeedController {
    @Autowired
    private SpeedService speedService;

    @PostMapping("oil/latestdata/fetchfiletransferprogress")
    @ResponseBody
    public HashMap<String, Object> getCurrentSpeed(@RequestBody HashMap<String,String> request) {
        String eui = request.get("eui");
        HashMap<String, Object> map = new HashMap<>();
        try (FileWriter fileWriter = new FileWriter("logging.txt")) {
            Speed speed = speedService.getSpeedNow(eui);
            fileWriter.write("执行");

            if (speed != null) {
                fileWriter.write(String.valueOf(speed.getTotalFileNum()));
                map.put("status", 200);
                map.put("msg", "OK");
                map.put("data", new SubSpeed(speed.getTotalFileNum(), speed.getAcceptFileNum(), speed.getSpeed()));
                fileWriter.write(map.get("data").toString());
            } else {
                map.put("code", 300);
                map.put("msg", "failed");
                map.put("data", null);
            }
        } catch (Exception e) {
            System.out.println(Arrays.toString(e.getStackTrace()));
            map.put("code", 800);
            map.put("msg", "try-catch error");
        }
        return map;
    }
}
